import Mock from 'mockjs'

// get请求
function param20bj (url: string) {
  const search = url.split('?')[1]
  if (!search) return {};
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}'
  )
}

let lst: any[] = []
for (let i=0; i < 30; i++) {
  lst.push (
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      addr: Mock.mock('@county(true)'),
      'age|18-60': 1,
      birth: Mock.Random.date(),
      sex: Mock.Random.integer(0, 1)
    })
  )
}

export default {
  
  /**
   * 获取用户列表
   * @param config 
   * @returns 
   */
  getUserList: (config: { url: string; }) => {
    const { name, page = 1, limit = 20 } = param20bj(config.url);
    // console.log('name:' + name, 'page:' + page, 'limit:' + limit);
    const mockList = lst.filter(user => {
      if (name && user.name.indexOf(name) === -1 && user.addr.indexOf(name) === -1) 
        return false;
      return true;
    })
    const pageList = mockList.filter((item, index) => {
      return index < limit * page && index >= limit * (page - 1)
    })
    return {
      code: 2000,
      count: mockList.length,
      list: pageList
    }
  },

  /**
   * 添加用户
   * @param config 
   * @returns 
   */
  createUser: (config: { body: string; }) => {
    const { name, addr, age, birth, sex } = JSON.parse(config.body);
    lst.unshift({
      id: Mock.Random.guid(),
      name: name,
      addr: addr,
      age: age,
      birth: birth,
      sex: sex
    })
    return {
      code: 2000,
      data: {
        message: '添加成功'
      }
    }
  },

  /**
   * 删除用户
   * @param config 
   * @returns 
   */
  deleteUser: (config: { url: string; }) => {
    const { id } = param20bj(config.url);
    if (!id) {
      return {
        code: 999,
        message: '参数不正确'
      }
    } else {
      lst = lst.filter( u => u.id !== id);
      return {
        code: 2000,
        message: '删除成功'
      }
    }
  },

  /**
   * 批量删除用户
   * @param config 
   * @returns 
   */
  batchRemove: (config: { url: string; }) => {
    let { ids } = param20bj(config.url);
    ids = ids.split(',');
    lst = lst.filter(u => ids.include(u.id));
    return {
      code: 2000,
      data: {
        message: '批量删除成功'
      }
    }
  },

  updateUser: (config: { body: string; }) => {
    const { id, name, addr, age, birth, sex } = JSON.parse(config.body);
    const sexNum = parseInt(sex);
    lst.some(u => {
      if (u.id === id) {
        u.name = name;
        u.addr = addr;
        u.age = age;
        u.birth = birth;
        u.sex = sexNum
        return true;
      }
    })
    return {
      code: 2000,
      data: {
        message: '编辑成功'
      }
    }
  }
}

